package com.kuanter.kuanterauto.utils;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.json.JSONException;
import org.json.JSONObject;
/**
 * 字符串工具类
 * @author soup
 *
 */
public class StringUtils {
	/*
	 * MD5加密
	 */
	public static String MD5(String str) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		char[] charArray = str.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++) {
			byteArray[i] = (byte) charArray[i];
		}
		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	/**
	 * 判断返回json数据status值是否为true
	 * 
	 * @param result
	 * @return
	 * @throws JSONException
	 */
	public static boolean isSuccess(String result) throws JSONException {
		JSONObject jobj = new JSONObject(result);
		if (!jobj.optString("status").equals("false")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获得返回数据中 errorMsg 字段值
	 * 
	 * @param result
	 * @return
	 * @throws JSONException
	 */
	public static String geterrorMsg(String result) throws JSONException {
		JSONObject jobj = new JSONObject(result);
		if (!jobj.optString("errorMsg").equals("null")) {
			return jobj.optString("errorMsg");
		} else {
			return "请求失败";
		}
	}

	// 获得时间
	public static String getTime(long time) {
		Date now = new Date(time);
		// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
		TimeZone timeZoneChina = TimeZone.getTimeZone("GMT+8:00");// 获取中国的时区
		dateFormat.setTimeZone(timeZoneChina);
		return dateFormat.format(now);
	}
	
	
	// 获得小时
		public static String getHour(long time) {
			Date now = new Date(time);
			// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat dateFormat = new SimpleDateFormat("HH");
			TimeZone timeZoneChina = TimeZone.getTimeZone("GMT+8:00");// 获取中国的时区
			dateFormat.setTimeZone(timeZoneChina);
			return dateFormat.format(now);
		}
}
